package com.nf.health.app.myfamily.activity;

import android.app.AlertDialog;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.nf.health.app.Constants;
import com.nf.health.app.R;
import com.nf.health.app.activity.global.BaseActivity;
import com.nf.health.app.adapter.ViewHolder;
import com.nf.health.app.http.Apis;
import com.nf.health.app.models.UserInDevice;
import com.nf.health.app.utils.Code;
import com.nf.health.app.utils.DensityUtil;
import com.nf.health.app.utils.KeyBoardManager;
import com.nf.health.app.utils.LogUtil;
import com.nf.health.app.utils.ScreentUtils;
import com.nf.health.app.utils.ViewUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * @author Ian
 * @ClassName: AccountBindingActivity
 * @Description: 绑定页
 * @date 2015-11-4 上午9:35:27
 */
public class AccountBindingActivity extends BaseActivity {
    private static final String[] types = new String[]{"family", "oldMobile", "simple"};
    public static final int BINDING_HEALTHY_DEVICE = 0;
    public static final int BINDING_OLD_AGE_ACCOUNT = 1;
    public static final int BINDING_APP_ACCOUNT = 2;
    private static final String TAG = AccountBindingActivity.class.getSimpleName();
    private int type;
    private EditText et_device_num;
    private EditText et_device_pwd;
    private Button btn_binding;
    private EditText et_phone_num, et_imei_num, et_name_num;
    private EditText et_verification_code;
    private Button btn_get_code;
    private EditText et_app_num;
    private EditText et_app_pwd;
    private TextView tishi_imei;
    String et_ipone_num1;
    private AlertDialog alertDialog;
    private int screenWidth;
    private int margin;
    private int currentPos = -1;
    private List<UserInDevice> users;
    private List<Boolean> pos = new ArrayList<Boolean>();


    String et_iemi_num1, et_name_num1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        screenWidth = ScreentUtils.getScreenWidth(this);
        margin = DensityUtil.dip2px(this, 40);
        type = getIntent().getIntExtra("type", 0);
        setTitleBar(R.layout.titlebar_base);
        setContent(R.layout.activity_account_binding);

        initView();
    }

    private void initView() {
        btn_binding = ViewUtil.getView(this, R.id.btn_binding);
        switch (type) {
            case BINDING_HEALTHY_DEVICE:
                ViewUtil.setText(this, R.id.titlebar_title_tv, "绑定健管机");
                View ll_healthy_device = ViewUtil.getView(this, R.id.ll_healthy_device);
                et_device_num = ViewUtil.getView(this, R.id.et_device_num);
                et_device_pwd = ViewUtil.getView(this, R.id.et_device_pwd);
                ll_healthy_device.setVisibility(View.VISIBLE);
                btn_binding.setText("获取健管机下用户");
                break;
            case BINDING_OLD_AGE_ACCOUNT:
                ViewUtil.setText(this, R.id.titlebar_title_tv, "绑定老年手机账号");
                View ll_old_age_account = ViewUtil.getView(this, R.id.ll_old_age_account);
                et_imei_num = ViewUtil.getView(this, R.id.et_iemi_num);
                et_name_num = ViewUtil.getView(this, R.id.et_name_num);
                et_phone_num = ViewUtil.getView(this, R.id.et_phone_num);
                tishi_imei = ViewUtil.getView(this, R.id.tishi_imei);
                et_verification_code = ViewUtil.getView(this, R.id.et_verification_code);
                btn_get_code = ViewUtil.getView(this, R.id.btn_get_code);
                btn_get_code.setOnClickListener(this);
                ll_old_age_account.setVisibility(View.VISIBLE);
                tishi_imei.setVisibility(View.VISIBLE);
                break;
            case BINDING_APP_ACCOUNT:
                ViewUtil.setText(this, R.id.titlebar_title_tv, "绑定爱尚康账号");
                View ll_app_account = ViewUtil.getView(this, R.id.ll_app_account);
                et_app_num = ViewUtil.getView(this, R.id.et_app_num);
                et_app_pwd = ViewUtil.getView(this, R.id.et_app_pwd);
                ll_app_account.setVisibility(View.VISIBLE);
                break;
        }
        btn_binding.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_binding:
                switch (type) {
                    case BINDING_HEALTHY_DEVICE:
                        //TODO 首先根据设备号和设备密码获取健管机下用户列表，获取到用户列表再进行绑定操作
                        KeyBoardManager.closeKeyboard(this, et_device_num);
                        String device_num = et_device_num.getText().toString();
                        String device_pwd = et_device_pwd.getText().toString();

                        if (TextUtils.isEmpty(device_num) || TextUtils.isEmpty(device_pwd)) {
                            showToast("设备编号或密码为空");
                            return;
                        }

                        provider.requestGetDeviceUser(device_num, device_pwd, "getDeviceUsers");
//				provider.requestAcount(types[BINDING_HEALTHY_DEVICE],device_num, device_pwd, "", "bindAppAccount");

                        break;
                    case BINDING_OLD_AGE_ACCOUNT:

                        et_iemi_num1 = et_imei_num.getText().toString();
                        et_name_num1 = et_name_num.getText().toString();
                        et_ipone_num1 = et_phone_num.getText().toString();
                        String et_verification_code1 = et_verification_code.getText().toString();

                        if (TextUtils.isEmpty(et_iemi_num1)) {
                            showToast("IMEI号未输入");

                        } else if (et_iemi_num1.length() != 15) {

                            showToast("IMEI号输入格式不正确");

                        } else if (TextUtils.isEmpty(et_ipone_num1)) {
                            showToast("手机号未输入");
                        } else if (TextUtils.isEmpty(et_verification_code1)) {
                            showToast("验证码未输入");
                        } else if (TextUtils.isEmpty(et_name_num1)) {
                            showToast("昵称未输入");
                        } else {
                            //绑定操作
//					provider.requestMSGCodeCode(et_ipone_num1, et_verification_code1, "verifycode", "yanzheng");
                            //绑定老年手机需要验证码,昵称
                            provider.requestAcount(types[BINDING_OLD_AGE_ACCOUNT], et_iemi_num1, et_ipone_num1, et_verification_code1, Constants.SMS_FAMLIY, et_name_num1, "bindAccount");
                        }

                        break;
                    case BINDING_APP_ACCOUNT:
                        KeyBoardManager.closeKeyboard(this, et_app_num);
                        String app_num = et_app_num.getText().toString();
                        String app_pwd = et_app_pwd.getText().toString();
                        if (TextUtils.isEmpty(app_num) || TextUtils.isEmpty(app_pwd)) {
                            showToast("账号或密码为空");
                            return;
                        }
                        //绑定app账号不需验证码,nick,等
                        provider.requestAcount(types[BINDING_APP_ACCOUNT], app_num, app_pwd, "", "", "", "bindAccount");
                        break;
                    default:
                        break;
                }
                break;
            case R.id.btn_get_code:
                et_ipone_num1 = et_phone_num.getText().toString();
                if (TextUtils.isEmpty(et_ipone_num1)) {
                    showToast("手机号码不能为空!");
                    break;
                }
                if (et_ipone_num1.length() != 11) {
                    showToast("手机号码输入错误！");
                    break;
                }
                Constants.LOCAL_CODE = Code.getInstance().getCode();
                LogUtil.i(TAG, Constants.LOCAL_CODE);
                provider.requestMSGCode(et_ipone_num1, Constants.SMS_FAMLIY, "verifycode");
                break;
        }
        super.onClick(v);
    }

    @Override
    public void handleActionSuccess(String actionName, Object object) {
        if ("getDeviceUsers".equals(actionName)) {
            users = (List<UserInDevice>) object;

            showDialog();
        }
        if ("bindAccount".equals(actionName)) {
            showToast("绑定成功");
            setResult(RESULT_OK);
            finish();
        }
        if (actionName.equals("verifycode")) {
            hideLoading();
            if (Apis.HOST_COMMON.contains("test.")) {
                //返回验证码, 自动添加到框里, 发包时注释掉
                String code = null;
                try {
                    code = new JSONObject((String) object).optJSONObject("data").optString("verifycode");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                et_verification_code.setText(code);
            }
            showToast("验证码发送成功！");
        }
    }

    private void showDialog() {
        final AlertDialog.Builder build = new AlertDialog.Builder(this);
        alertDialog = build.create();
        alertDialog.show();//必须在设置View之前调用
        alertDialog.setCanceledOnTouchOutside(false);
        View view = View.inflate(this, R.layout.dialog_device_user, null);
        alertDialog.setContentView(view);

        Button btn_submit = (Button) alertDialog.findViewById(R.id.btn_submit);
        ListView listview = (ListView) alertDialog.findViewById(R.id.listview);
        final DeviceUserAdapter deviceUserAdapter = new DeviceUserAdapter();
        listview.setAdapter(deviceUserAdapter);
        btn_submit.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (alertDialog != null)
                    alertDialog.dismiss();
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < users.size(); i++) {
                    if (pos.get(i)) {
                        sb.append(users.get(i).getUserid() + ",");
                    }
                }
                String substring = sb.substring(0, sb.length() - 1);
                showToast(substring);

                provider.requestBindBox(substring, "bindAccount");
            }
        });
    }

    class DeviceUserAdapter extends BaseAdapter {
        public DeviceUserAdapter() {
            for (int i = 0; i < users.size(); i++) {
                pos.add(false);
            }
        }

        @Override
        public int getCount() {
            return users == null ? 0 : users.size();
        }

        @Override
        public Object getItem(int position) {
            return users.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            ViewHolder holder = ViewHolder.get(parent, convertView, R.layout.item_device_user, position);
            holder.setText(R.id.tv_userno, users.get(position).getBoxno());
            holder.setText(R.id.tv_usernick, users.get(position).getNick());
            CheckBox cb_select = holder.getView(R.id.cb_select);
            cb_select.setChecked(pos.get(position));
            cb_select.setTag(position);
            cb_select.setOnCheckedChangeListener(new OnCheckedChangeListener() {

                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    buttonView.setChecked(isChecked);
                    pos.set(position, isChecked);
                }
            });
            return holder.getConvertView();
        }

    }
}
